﻿using System;
using System.Collections; 
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using System.Collections.Generic;

namespace Hisun.View.SCRB
{
    public partial class Scrb_Daily_Collect : System.Web.UI.Page
    { 
        
        private string mypipID;
        int mycostcenterID;
        DateTime dt_myday;
        public string alter;

        HisunDBDataContext db = new HisunDBDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            mypipID = HttpUtility.UrlDecode(Request.QueryString["mypip"]);
            dt_myday = DateTime.Parse(HttpUtility.UrlDecode(Request.QueryString["myday"]));
            bindmypip();

            if (!IsPostBack)
            {

                BindEmptyData();
            }
        }

        /// <summary>
        /// 获取当前会计期间
        /// </summary>
        /// <param name="it_date"></param>
        /// <returns></returns>
        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk = (from a in db.TABC_JS_AccountPeriod
                        where a.成本开始日期 <= it_date
                               && a.成本结账日期 >= it_date
                        select a.会计期间ID).Single();

            return kjqk;
        }
        private string getAccoutperiod()
        {
            return getAccoutperiod(this.dt_myday);
        }

        private void bindmypip()
        {
            var mypip = (from a in db.TABC_JS_ProductInProcess
                         where a.中间体ID == mypipID
                         select a).Single();


            mycostcenterID = (int)mypip.作业中心ID;
            string mycostcentername = (from a in db.TABC_JS_CostCenter
                                       where a.作业中心ID == mycostcenterID
                                       select a.作业中心名称).Single();

            Label_CostCenter.Text = mycostcentername;
            Label_PIPNAME.Text = mypip.中间体名称;
            Label_myday.Text = dt_myday.ToShortDateString();



        }

        private string splitbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                batch = batch.Split('/')[1];
            }

            return batch;
        }

        private string joinbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                return batch;
            }
            return this.mypipID + "/" + batch;
            
        }

        
        protected void BindEditData(string BatchNumber)
        {
            Guid Guid1 = Guid.Empty;
            try
            {
                  Guid1 = (from a in db.TSCRB_JS_BatchColletionInfo
                                    where a.批号 == BatchNumber
                                    select a.包ID).Single();
            }
            catch
            {
                Label_alter.Text = "批号：" + BatchNumber + "还未拆批，不能编辑";
                alter = "<script>alert('批号：" + BatchNumber + "还未拆批，不能编辑!');</script>";
                BindEmptyData();
                return;

            }

            BindEditData(Guid1);

        }


        private void BindEditData(Guid Guid1)
        {

            var q = (from a in db.TSCRB_JS_BatchColletionRelate
                     where a.包ID == Guid1 || a.原包ID == Guid1
                     select a).Single();
            Guid Package_From = q.原包ID;
            Guid Package_For = q.包ID;

            BindLeft(Package_From);
            BindRight(Package_For);  //目标
        }
        /// <summary>
        /// 绑定右边的Gridview3
        /// </summary>
        /// <param name="RightPackage"></param>
        private void BindRight(Guid RightPackage)
        {
            DataTable dt2 = new DataTable();
            dt2.Columns.Add("ID");
            dt2.Columns.Add("新批号");
            dt2.Columns.Add("拆并批系数");


            var q3 = (from a in db.TSCRB_JS_BatchColletionInfo
                      where a.包ID == RightPackage
                      select a);
            foreach (var row in q3)
            {
                dt2.Rows.Add(new object[]{row.ID,splitbatch(row.批号),row.拆批系数});
            }
           for(int i=0;i<=5;i++)
           {
               dt2.Rows.Add(new object[] { 0, "", 1 });
           }
           dt2.AcceptChanges();
           GridView3.DataSource = dt2;
           GridView3.DataBind();
           

        }
        /// <summary>
        /// 绑定左边的GridView         
        /// </summary>
        /// <param name="leftPackpage"></param>
        private void BindLeft(Guid leftPackpage)
        {

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("拆并批", typeof(bool));
            dt1.Columns.Add("允许拆批", typeof(bool));
            dt1.Columns.Add("批号");
            dt1.Columns.Add("状态");
            dt1.Columns.Add("允许编辑",typeof(bool));
            var q4 = (from a in db.TSCRB_JS_BatchColletionInfo
                      where a.包ID == leftPackpage
                      select a); //源
            foreach (var row in q4)
            {
                dt1.Rows.Add(new object[] { row.ID, true, true, row.批号, "原批号",true });
            }
            var q5 = (from a in db.TSCRB_JS_BatchInfo
                      join b in db.TSCRB_DM_BatchStatus on
                      a.批号类型 equals b.DM
                      join c in db.TSCRB_JS_BatchInfoDetail
                      on a.批号 equals c.批号
                      where a.批号类型 == "P" && c.中止日期 < dt_myday                  
                      && a.中间体ID == mypipID
                      select new
                      {

                          ID = a.ID,
                          拆并批 = false,
                          允许拆批 = (a.批号类型 == "P"),
                          批号 = a.批号,
                          b.状态,
                          允许编辑 =false
                      });

            foreach (var row in q5)
            {
                dt1.Rows.Add(new object[] { row.ID, row.拆并批, row.允许拆批, row.批号, row.状态,row.允许编辑 });
            }
            dt1.AcceptChanges();
            GridView1.DataSource = dt1;
            GridView1.DataBind();

 


        }


        /// <summary>
        /// 初始绑定Girdview
        /// </summary>
        protected void BindEmptyData()
        { 
            var qs = (from a in db.TSCRB_JS_BatchInfo
                      join b in db.TSCRB_DM_BatchStatus on
                      a.批号类型 equals b.DM
                      join c in db.TSCRB_JS_BatchInfoDetail
                      on a.批号 equals c.批号
                      where a.批号类型 == "P"
                       && a.中间体ID == mypipID
                       && c.中止日期 < dt_myday
                      select new
                      {

                          ID = a.ID,
                          拆并批 = false,
                          允许拆批 = (a.批号类型 == "P"),
                          批号 = a.批号,
                          b.状态,
                          允许编辑 = (a.批号类型 != "P"),
                      }).Concat(
                      from a in db.TSCRB_JS_BatchInfo
                      join b in db.TSCRB_DM_BatchStatus
                      on a.批号类型 equals b.DM
                      join c in db.TSCRB_JS_BatchInfoDetail on
                      a.批号 equals c.批号
                      where a.批号类型 == "C" && c.投入日期 == dt_myday && c.中止日期 == null 
                      select new
                      {
                          ID = c.ID,
                          拆并批= false,
                          允许拆批 = (a.批号类型 == "P"),
                          批号 = a.批号,
                          b.状态,
                          允许编辑 = (a.批号类型 != "P"),
                      }
                      );
            

            GridView1.DataSource = qs;

            GridView1.DataBind();

            if (qs.Count() == 0)
            {
                alter = "<script>alert('没有可以拆并批的批号。');</script>";
                return;
                
            }
            DataTable dt2 = new DataTable();
            dt2.Columns.Add("ID");
            dt2.Columns.Add("新批号");
            dt2.Columns.Add("拆并批系数");
 
            for (int i = 0; i <= 5; i++)
            {
                dt2.Rows.Add(new object[] { 0, "", 1 });
            }
            dt2.AcceptChanges();
            GridView3.DataSource = dt2;
            GridView3.DataBind();
           

        }
        protected DataTable GetLeftData(out int   count)
        {
            count = 0;
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("拆并批");
            dt1.Columns.Add("批号"); 
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gRow = GridView1.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView1.DataKeys[i].Value;
                newRow[1] = ((CheckBox)gRow.FindControl("CheckBox1")).Checked;
                newRow[2] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                //if (newRow[1].ToString() == "True")
                //{
                    dt1.Rows.Add(newRow);
                //}
                    if (newRow[1].ToString() == "True")
                    {
                        count++;
                    }
            }
            dt1.AcceptChanges();
            return dt1;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="count">数据个数</param>
        /// <param name="count2">非空数据个数</param>
        /// <returns></returns>
        protected DataTable GetRightData(out int count,out int count2)
        {
            count = 0;
            count2 = 0;
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID"); 
            dt1.Columns.Add("新批号");
            dt1.Columns.Add("拆并批系数");
            for (int i = 0; i < GridView3.Rows.Count; i++)
            {
                GridViewRow gRow = GridView3.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView3.DataKeys[i].Value;
                newRow[1] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                newRow[2] = ((TextBox)gRow.FindControl("TextBox2")).Text;
                //  if (newRow[1].ToString().Trim().Length >0)
                // {
                dt1.Rows.Add(newRow);
                //  }
                if (newRow[0].ToString() != "0")  
                {
                  //   ++count2;
                    ++count;
                }
                   if (newRow[1].ToString().Length > 1)
                {
                    ++count2;
                }
            }
            dt1.AcceptChanges();
            return dt1;
        }


        private bool checkbachexist(string batchnumber)
        {
            if (batchnumber.IndexOf('/') < 0)
            {
                batchnumber = joinbatch(batchnumber);
            }
            var q = from a in db.TSCRB_JS_BatchInfo
                    where
                        a.批号 == batchnumber
                    select a;
            if (q.Count() > 0)
            {
                return true;
            }
            return false;

        }

        private void UpdateTransRate(string Batch)
        {
            double sumrate = (from a in db.TSCRB_JS_Out
                              where a.批号 == Batch
                              select a.转出系数).Sum().Value;

            var q = (from a in db.TSCRB_JS_BatchInfo where a.批号 == Batch select a).Single();
            q.转出率 = sumrate;
            db.SubmitChanges();
        }

        private bool DeleteRate(Guid ID)
        {
            var q = from a in db.TSCRB_JS_BatchColletionRelate
                    where a.包ID == ID || a.原包ID == ID
                    select a;
            
            db.TSCRB_JS_BatchColletionRelate.DeleteAllOnSubmit(q);
            try
            {
                db.SubmitChanges();

            }
            catch
            {
                return false;
            }
            return true;


        }
        private bool DeletePackage(Guid ID)
        {
            var q = from a in db.TSCRB_JS_BatchColletionInfo
                    where a.包ID == ID
                    select a;
            db.TSCRB_JS_BatchColletionInfo.DeleteAllOnSubmit(q);
            try
            {
                db.SubmitChanges();

            }
            catch
            {
                return false;
            }
            return true;


        }

        private bool DeleteBatchFormPackage(string BatchID)
        {
            var q = from a in db.TSCRB_JS_BatchColletionInfo
                    where a.批号 == BatchID
                    select a;
            try
            {
                db.TSCRB_JS_BatchColletionInfo.DeleteAllOnSubmit(q);
                
                var info = (from a in db.TSCRB_JS_BatchInfo
                            where a.批号 == BatchID
                            select a).Single();
               switch (info.批号类型)
               { 
                   case "Z":
                       info.批号类型 = "P";
                       break;
                   case "C":
                       DeleteBatch(BatchID);
                       break;               
                    
               }

            }
            catch
            {
                return false;
            }
            return true;
                     
        }
        private bool DeleteBatch(string BatchID)
        {
            var q = from a in db.TSCRB_JS_BatchInfo
                    where a.批号 == BatchID
                    select a;
            var q2 = from a in db.TSCRB_JS_BatchInfoDetail
                     where a.批号 == BatchID
                     select a;
            db.TSCRB_JS_BatchInfoDetail.DeleteAllOnSubmit(q2);
            db.TSCRB_JS_BatchInfo.DeleteAllOnSubmit(q);
            try
            {
                db.SubmitChanges();
            }
            catch
            {
                return false;
            }
            return true;

        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button_Save_Click(object sender, EventArgs e)
        {
            Label_alter.Text = "";

            Label_alter.ForeColor = System.Drawing.Color.Red;
            int count_right2;
            int count_dt_left, count_td_right;
            DataTable dt1 = GetLeftData( out count_dt_left);
            DataTable dt2 = GetRightData(out count_td_right,out  count_right2);
            

            Guid Package_From= Guid.Empty;
            Guid   Package_For=Guid.Empty;
            int i = 0;
            List<string> PackageBatchs_from = new List<string>(); 
            List<string> PackageBatchs_for= new List<string>() ;
            TSCRB_JS_BatchColletionRelate Package_Rate=null;


            DataRow row = dt2.Rows[0];

            if ( (count_td_right+count_right2)==0)
            {


                Label_alter.Text = "没有填写任何批号";

                alter = "<script>alert('没有填写任何新批号');</script>";


                BindEmptyData();

                return;
            }
            if (count_td_right>0 &&count_right2 == 0 && count_dt_left > 0)
            {
                 
                foreach (DataRow row1 in dt1.Rows)
                { 
                    
                     var q = (from a in db.TSCRB_JS_BatchColletionInfo
                              where a.批号 == joinbatch(row1["批号"].ToString())
                                 select a);
                     if (q.Count() == 1)
                     {
                         //已有数据，删除
                         db.TSCRB_JS_BatchColletionInfo.DeleteAllOnSubmit(q);
                         try
                         {
                             var update = (from a in db.TSCRB_JS_BatchInfo
                                           where a.批号 == joinbatch(row1["批号"].ToString()) && a.批号类型 == "Z" //把结束状态重新改为中止
                                           select a).Single();
                             update.批号类型 = "P";
                             //var info2 = from a in db.TSCRB_JS_BatchColletionInfo
                         }
                         catch
                         {
                         }
                        

                     }
                    
                }
                db.SubmitChanges();

                alter = "<script>alert('删除拆并批状态成功');</script>";
                BindEmptyData();
                return;

            }
            if (count_dt_left == 0 && count_td_right >0)
            {
                foreach (DataRow row1 in dt1.Rows)
                {

                    var q = (from a in db.TSCRB_JS_BatchColletionInfo
                             where a.批号 == joinbatch(row1["批号"].ToString())
                             select a);
                    if (q.Count() == 1)
                    {
                        //已有数据，删除
                        db.TSCRB_JS_BatchColletionInfo.DeleteAllOnSubmit(q);
                        try
                        {
                            var update = (from a in db.TSCRB_JS_BatchInfo
                                          where a.批号 == joinbatch(row1["批号"].ToString()) && a.批号类型 == "Z" //把结束状态重新改为中止
                                          select a).Single();
                            update.批号类型 = "P";
                            //var info2 = from a in db.TSCRB_JS_BatchColletionInfo
                        }
                        catch
                        {
                        }


                    }

                }
                db.SubmitChanges();
                alter = "<script>alert('删除拆并批状态成功');</script>";
              

                BindEmptyData();

                return;
                
            }

            /*
             * 左边没有选择任何项目，而右边写了新批号        
             
             */
            if (count_dt_left == 0 && count_right2 > 0) 
            {
                alter = "<script>alert('没有选择任何原批号');</script>";  //警告用户让他重新填
                

                return;//返回，退出操作
            }

            if (row["ID"].ToString() != "0") //说明已经有数据
            {
                var q1 = (from a in db.TSCRB_JS_BatchColletionInfo
                          where a.ID == long.Parse(row["id"].ToString())
                          select a).Single();

                Package_For = q1.包ID;
               PackageBatchs_for = (from a in db.TSCRB_JS_BatchColletionInfo
                               where a.包ID == Package_For
                                                  select a.批号).ToList<string>();
                 
                Package_From = (from a in db.TSCRB_JS_BatchColletionRelate
                                where a.包ID == Package_For
                                select a.原包ID).Single();
                PackageBatchs_from = (from a in db.TSCRB_JS_BatchColletionInfo
                                      where a.包ID == Package_From
                                      select a.批号).ToList<string>();


            }
            else
            {
                Package_From = Guid.NewGuid();
                Package_For = Guid.NewGuid();
                Package_Rate= new TSCRB_JS_BatchColletionRelate();
                Package_Rate.包ID = Package_For;
                Package_Rate.会计期间ID = getAccoutperiod();
                Package_Rate.中间体ID = mypipID;
                Package_Rate.原包ID = Package_From;
              //  db.TSCRB_JS_BatchColletionRelate.InsertOnSubmit(Package_Rate);
                //db.SubmitChanges();

                
            
            }

            ///修改新批号的包
            foreach (DataRow row2 in dt2.Rows)
            {
                if (row2["新批号"].ToString().Trim().Length > 0)
                {
                    i++;
                    string 新批号 = joinbatch(row2["新批号"].ToString());
                    if (checkbachexist(新批号))
                    {
                        Label_alter.Text += splitbatch(新批号) + "已存在";
                        alter = "<script>alert('" + splitbatch(新批号) + "已存在');</script>";
                        return;
                    }

                    if (row2["ID"].ToString() != "0") //说明已经有数据
                    {
                        var editFor = (from a in db.TSCRB_JS_BatchColletionInfo
                                       where a.ID == long.Parse(row2["ID"].ToString())
                                       select a).Single();
                        PackageBatchs_for.Remove(editFor.批号); //

                        if (editFor.批号 == 新批号)
                        {
                            editFor.拆批系数 = double.Parse(row2["拆并批系数"].ToString());
                        }
                        else
                        {
                            //修改成新批号
                            var editInfo = (from a in db.TSCRB_JS_BatchInfo
                                            where a.批号 == editFor.批号
                                            select a).Single();
                            var editdetail = (from a in db.TSCRB_JS_BatchInfoDetail
                                              where a.批号 == editFor.批号
                                              select a).Single();
                            editdetail.批号 = 新批号;
                            editInfo.批号 = 新批号;
                            editFor.批号 = 新批号;
                            editFor.拆批系数 = double.Parse(row2["拆并批系数"].ToString());


                        }
                        db.SubmitChanges();
                    }
                    else // out id is null ,   insert a line into  out table
                    {
                        //int Packcount = (from a in db.TSCRB_JS_BatchColletionInfo
                        //                 where a.包ID == Package_For
                        //                 select a).Count();
                        //if (Packcount > 0)
                        //{

                        //}

                        TSCRB_JS_BatchColletionInfo P1 = new TSCRB_JS_BatchColletionInfo();
                        P1.包ID = Package_For;
                        P1.批号 = 新批号;
                        P1.拆批系数 = double.Parse(row2["拆并批系数"].ToString());
                        db.TSCRB_JS_BatchColletionInfo.InsertOnSubmit(P1);
                        //  db.SubmitChanges();

                        TSCRB_JS_BatchInfo Pinfo = new TSCRB_JS_BatchInfo();
                        Pinfo.会计期间ID = getAccoutperiod();
                        Pinfo.批号 = 新批号;
                        Pinfo.批号类型 = "C";
                        Pinfo.中间体ID = mypipID;
                        Pinfo.折批系数 = double.Parse(row2["拆并批系数"].ToString());

                        db.TSCRB_JS_BatchInfo.InsertOnSubmit(Pinfo);
                        //db.SubmitChanges();
                        TSCRB_JS_BatchInfoDetail Pdetail = new TSCRB_JS_BatchInfoDetail();
                        Pdetail.会计期间ID = getAccoutperiod();
                        Pdetail.批号 = 新批号;
                        Pdetail.投入日期 = dt_myday;
                        Pdetail.中间体ID = mypipID;

                        db.TSCRB_JS_BatchInfoDetail.InsertOnSubmit(Pdetail);

                        db.SubmitChanges();



                    }//if (row2["ID"].ToString() != "0") 
                }//if (newRow[1].ToString().Trim().Length >0)
            }//for each

            int j = 0;

            ///修改原批号的包
                foreach (DataRow row3 in dt1.Rows)
                {
                    
                    string 批号 = joinbatch(row3["批号"].ToString());
                    if (row3["拆并批"].ToString() == "True")
                    {
                        j++;
                        var q = (from a in db.TSCRB_JS_BatchColletionInfo
                                 where a.批号 == 批号
                                 select a);
                        if (q.Count() == 1)
                        {
                            //已有数据，不变
                        }
                        else
                        {
                            var newForm = new TSCRB_JS_BatchColletionInfo();
                            newForm.包ID = Package_From;
                            newForm.拆批系数 = 1;
                            newForm.批号 = 批号;
                            db.TSCRB_JS_BatchColletionInfo.InsertOnSubmit(newForm);


                            var updateFromInfo = (from a in db.TSCRB_JS_BatchInfo
                                                  where a.批号 == 批号
                                                  select a).Single();
                            updateFromInfo.批号类型 = "Z";

                            
                        }
                        db.SubmitChanges();
                    }
                    else
                    {
                        var q = (from a in db.TSCRB_JS_BatchColletionInfo
                                 where a.批号 == 批号
                                 select a);
                        if (q.Count() == 1)
                        {
                            //已有数据，删除
                            db.TSCRB_JS_BatchColletionInfo.DeleteAllOnSubmit(q);
                            try
                            {
                                var update = (from a in db.TSCRB_JS_BatchInfo
                                              where a.批号 == 批号 && a.批号类型=="Z" //把结束状态重新改为中止
                                              select a).Single();
                                update.批号类型 = "P";
                            }
                            catch
                            {
                            }
                            

                        }
                        db.SubmitChanges();
                    } 

                }//for each dt1



                if (PackageBatchs_for.Count > 0)
                {
                    foreach (string delteBatchs in PackageBatchs_for)
                    {
                        var deleteinfo = from a in db.TSCRB_JS_BatchInfo
                                         where a.批号 == delteBatchs
                                         select a;
                        var deletedetail = from a in db.TSCRB_JS_BatchInfoDetail
                                           where a.批号 == delteBatchs
                                           select a;

                        db.TSCRB_JS_BatchInfo.DeleteAllOnSubmit(deleteinfo);
                        db.TSCRB_JS_BatchInfoDetail.DeleteAllOnSubmit(deletedetail);
                    }
                }


                db.SubmitChanges();
            var q_from= from a in db.TSCRB_JS_BatchColletionInfo where a.包ID == Package_From select a;
            var q_for =from a in db.TSCRB_JS_BatchColletionInfo where a.包ID ==Package_For select a ;

            if (q_for.Count() == 0 || q_from.Count() == 0)
            {

                try
                {
                    var deleterate = from a in db.TSCRB_JS_BatchColletionRelate
                                     where a.包ID == Package_For
                                     select a;
                    db.TSCRB_JS_BatchColletionRelate.DeleteAllOnSubmit(deleterate);
                    db.SubmitChanges();
                    

                }
                catch
                {
                }
                BindEmptyData();

                return;
            }
            else
            {
                db.TSCRB_JS_BatchColletionRelate.InsertOnSubmit(Package_Rate);
               db.SubmitChanges();
            }
            
            

            Label_alter.Text += "保存成功";
            alter = "<script>alert('保存成功');</script>";
            
         //   BindEmptyData();
            BindEditData(Package_For);

        }



        protected void EditColl(object sender, CommandEventArgs e)
        {
            string 批号 = e.CommandArgument.ToString();

            BindEditData(批号);
        }

        protected void Button_Back_Click(object sender, EventArgs e)
        {
            Response.Redirect("Scrb_Daily_MainPage.aspx?centerid=" + mycostcenterID.ToString() + "&PIPid=" + mypipID);
      
        }

    }
}
